package com.example.treehole.ui.component

import android.annotation.SuppressLint
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material.icons.filled.ThumbUpOffAlt
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import com.example.treehole.LocalNavController
import com.example.treehole.LocalPostDetailViewModel
import com.example.treehole.LocalUserViewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.model.Comment
import com.example.treehole.ui.theme.iconBlue
import com.example.treehole.ui.theme.mediumDarkGray
import com.example.treehole.ui.theme.postCyan
import kotlinx.coroutines.launch
import java.util.Locale

@SuppressLint("UnrememberedMutableInteractionSource")
@Composable
fun CommentCard(
    comment: Comment
) {
    val navController = LocalNavController.current
    val userViewModel = LocalUserViewModel.current
    val userId by userViewModel.userId.collectAsState()
    val jwlToken by userViewModel.jwlToken.collectAsState()
    val scope = rememberCoroutineScope()

    val postDetailViewModel = LocalPostDetailViewModel.current

    // 时间格式化
    val timeText = formatTime(comment.cmtTime, true)
    val isLike = remember { mutableStateOf(comment.isLike) }
    val likeCount = remember { mutableIntStateOf(comment.cmtLikeCount) }

    // 格式化评论ID
    val formatPostId = String.format(Locale.PRC, "#%08d", comment.postId)

    // 主评论卡片
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .border(1.dp, Color.Gray)
            .clickable(
                onClick = {
                    navController.navigate("postDetail")
                    scope.launch {
                        userId?.let {
                            postDetailViewModel.getPostDetail(
                                jwlToken,
                                comment.postId,
                                it
                            )
                        }
                    }
                }),
        colors = CardDefaults.cardColors(
            containerColor = postCyan
        ),
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(4.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .clip(RoundedCornerShape(8.dp))
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 12.dp, horizontal = 16.dp)
            ) {
                Text(
                    text = "在帖子" + formatPostId + "中",
                    color = Color.Gray,
                    style = MaterialTheme.typography.bodySmall
                )

                // 评论内容
                Text(
                    text =
                    buildAnnotatedString {
                        if (comment.type == 0 || comment.replyUserName == "") append("")
                        else {
                            append("回复 ")
                            withStyle(
                                style = SpanStyle(color = mediumDarkGray),
                                block = { append(comment.replyUserName) }
                            )
                            append(" : ")
                        }
                        append(comment.cmtContent)
                    },
//                    text = post.cmtContent,
                    style = MaterialTheme.typography.bodyMedium,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis
                )

                // 时间和互动按钮行
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    // 时间显示
                    Text(
                        text = timeText,
                        color = Color.Gray,
                        style = MaterialTheme.typography.bodySmall
                    )

                    // 点赞按钮
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceEvenly
                    ) {
                        // 点赞按钮
                        IconButton(
                            onClick = {
                                scope.launch {
                                    userId?.let {
                                        if (isLike.value && DataRepository.unlikeCmt(
                                                jwlToken,
                                                comment.cmtId,
                                                it
                                            )
                                            ||
                                            (!isLike.value && DataRepository.likeCmt(
                                                jwlToken,
                                                comment.cmtId,
                                                it
                                            ))
                                        ) {
                                            likeCount.intValue += if (isLike.value) -1 else 1
                                            isLike.value = !isLike.value
                                            comment.isLike = isLike.value
                                            comment.cmtLikeCount = likeCount.intValue
                                        }
                                    }
                                }
                            },
                            modifier = Modifier.size(20.dp)
                        ) {
                            Icon(
                                imageVector = if (isLike.value) Icons.Default.ThumbUp else Icons.Default.ThumbUpOffAlt,
                                contentDescription = "Like",
                                tint = iconBlue
                            )
                        }

                        // 点赞数量
                        Text(
                            text = numberTransfer(likeCount.intValue)
                        )
                    }
                }
            }
        }
    }
}
